<?php

/**
 * uniBoard Reset Password
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-15 17:35:38 +0000 (Wed, 15 Sep 2010) $
 * $Revision: 61 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_rpass{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore		= NULL;
	
	/**
	 * Our User API
	 *
	 * @var object
	 */
	
	private $api			= NULL;
	
	/**
	 * Our ReCaptcha
	 *
	 * @var object
	 */
	
	private $recaptcha		= NULL;
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;
		
		// Load Language File
		$appCore -> loadLanguageFile( 'users');
				
		// User Logged In?
		if ( $appCore -> user['id'] > 0)
		{
			// Set Event
			$appCore -> output -> setEvent( $appCore -> lang['action_not_allowed_users'], $appCore -> lang['password_reset_title'], 0);
			
			// Run Events
			$appCore -> output -> drawEvents();
		}
		else if ( $appCore -> banned_ip)
		{
			// Set Event
			$appCore -> output -> setEvent( $appCore -> lang['action_not_allowed_ip'], $appCore -> lang['password_reset_title'], 0);
			
			// Run Events
			$appCore -> output -> drawEvents( true);
		}
		else if ( $appCore -> _REQ('done') == 1)
		{
			// Set Event
			$appCore -> output -> setEvent( $appCore -> lang['password_reset_first_step'], $appCore -> lang['password_reset_title'], 1);
			
			// Run Events
			$appCore -> output -> drawEvents( true, false);
		}
		else if ( $appCore -> _REQ('step') == 2)
		{
			// Make API
			$this -> api = new api_user( $appCore, $appCore -> _REQ('user'));
			
			// Try-Catch
			try
			{
				// User not found?
				if ( !$this -> api -> data_loaded)
				{
					throw new exc_small( $this -> appCore -> lang['api_user_not_found'], $this -> appCore -> lang['password_reset_title']);
				}
				
				// User not Active?
				if ( $this -> api -> user_activation != 0)
				{
					throw new exc_small( $this -> appCore -> lang['user_reset_not_active'], $this -> appCore -> lang['password_reset_title']);	
				}
				
				// Token not right?
				if ( strlen( $this -> api -> user_password_token) == 0 && $this -> api -> user_password_token != $appCore -> _REQ( 'token'))
				{
					throw new exc_small( $this -> appCore -> lang['user_reset_wrong_token'], $this -> appCore -> lang['password_reset_title']);	
				}
				
				// Generate new Password
				$new_pass = $appCore -> makeSalt( ceil(($appCore -> conf['user_password_lenght_min'] + $appCore -> conf['user_password_lenght_max']) / 2), false);
				
				// Update API
				$this -> api -> setUserPassword( $new_pass);
				
				// Make empty token
				$this -> api -> clearUserPasswordToken();
				
				// Save changes
				$this -> api -> saveData();
						
				// Redirect user
				$appCore -> setRedirect( $appCore -> niceLink( 'act=rpass&done=2', $appCore -> lang['password_reset_title']), false);
			
				// Keep Script Alive
				$appCore -> stayAlive();
				
				// Start our awesome Mailer
				$mailer = new class_mailer( $appCore);
				
				// Send User E-Mail
				$mailer -> sendEmail(
					$this -> api -> user_email,
					$this -> api -> user_name,
					$this -> appCore -> lang['email_password_new'],
					class_strings::parseMailText( file_get_contents( CACHE_PATH . 'lang_' . $this -> api -> user_language . '/email_password_reset_1.txt'), array(
						'{USER_NAME}' 				=> $this -> api -> user_name,
						'{USER_PASSWORD}' 			=> $new_pass,
						'{BOARD_NAME}' 				=> $this -> appCore -> conf['board_name'],
						'{BOARD_LOGIN_URL}' 		=> $this -> appCore -> emailLink( 'act=login', $this -> appCore -> lang['board_nav_login']),
						'{BOARD_URL}' 				=> $this -> appCore -> emailLink()
					)));
			}
			catch ( exc_small $exception)
			{
				// Set Error
				$this -> appCore -> output -> setEvent( $exception -> message, $exception -> title, 0);
		
				// Run Events
				$appCore -> output -> drawEvents( true);
			}
		}
		else if ( $appCore -> _REQ('done') == 2)
		{
			// Set Event
			$appCore -> output -> setEvent( $appCore -> lang['password_reset_second_step'], $appCore -> lang['password_reset_title'], 1);
			
			// Run Events
			$appCore -> output -> drawEvents( true, false);
		}
		else
		{	
			// Block login
			$appCore -> output -> show_login = false;
			
			// Start ReCAPTCHA?
			if ( $appCore -> conf['recaptcha_on_register'])
			{
				$this -> recaptcha = new class_recaptcha();
			}
						
			// Update?
			if ( $appCore -> _POST( 'send') == 1)
			{
				try
				{					
					// Captcha is invalid?
					if ( $this -> appCore -> conf['recaptcha_on_register'] && !$this -> recaptcha -> recaptcha_check())
					{
						throw new exc_small( $this -> appCore -> lang['recaptcha_incorrect_try_again'], $this -> appCore -> lang['recaptcha_incorrect']);
					}
					
					// Request is invalid?
					if ( !$this -> appCore -> validRequest())
					{
						throw new exc_small( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title']);
					}
					
					// Get User Login and EMail
					$user_login = $appCore -> _POST( 'user_login');
					$user_email = $appCore -> _POST( 'user_email');
					
					// One of them is empty?
					if ( !isset($user_login[0]) || !isset($user_email[0]))
					{
						throw new exc_small( $this -> appCore -> lang['user_cp_fields_all'], $this -> appCore -> lang['password_reset_title']);
					}
					
					// Find user?
					$this -> appCore -> db -> query( 'SELECT user_id, user_name, user_activation, user_email, user_language
					FROM ' . DB_PREFIX . 'users
					WHERE user_login LIKE \'' . $this -> appCore -> db -> strEscape( $user_login, true) . '\' AND user_email LIKE \'' . $this -> appCore -> db -> strEscape( $user_email, true) . '\' AND user_id > \'0\'');
					
					// User found?
					if ( $user_result = $this -> appCore -> db -> fetch_array())
					{
						// User Not Active?
						if ( $user_result[2] != 0)
						{
							throw new exc_small( $this -> appCore -> lang['user_reset_not_active'], $this -> appCore -> lang['password_reset_title']);	
						}
								
						// Redirect user
						$appCore -> setRedirect( $appCore -> niceLink( 'act=rpass&done=1', $appCore -> lang['password_reset_title']), false);
					
						// Keep Script Alive
						$appCore -> stayAlive();
						
						// Generate password token
						$token = $appCore -> makeSalt( 6, false);

						// Update User
						$appCore -> db -> update( array( 'user_password_token' => $token), 'users', 'user_id = \'' . $user_result[0] . '\'');
						
						// Start our awesome Mailer
						$mailer = new class_mailer( $appCore);
						
						// Send User E-Mail
						$mailer -> sendEmail(
							$user_result[3],
							$user_result[1],
							$this -> appCore -> lang['email_password_reset'],
							class_strings::parseMailText( file_get_contents( CACHE_PATH . 'lang_' . $user_result[4] . '/email_password_reset_0.txt'), array(
								'{USER_NAME}' 				=> $user_result[1],
								'{BOARD_NAME}' 				=> $this -> appCore -> conf['board_name'],
								'{BOARD_RESET_URL}' 		=> $this -> appCore -> emailLink( 'act=rpass&user=' . $user_result[0] . '&token=' . $token . '&step=2', $this -> appCore -> lang['password_reset_title']),
								'{BOARD_URL}' 				=> $this -> appCore -> emailLink()
							)));
					}
					else
					{
						// Not Found
						throw new exc_small( $this -> appCore -> lang['api_user_not_found_data'], $this -> appCore -> lang['password_reset_title']);
					}
					
					// Free Result
					$this -> appCore -> db -> freeResult();
				}
				catch ( exc_small $exception)
				{
					// Set Error
					$this -> appCore -> output -> setEvent( $exception -> message, $exception -> title, 0);
			
					// Throw us back to form
					$this -> drawForm();
				}
			}
			else
			{
				// Draw Form
				$this -> drawForm();
			}
		}
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Draws Manual Activation Form
	 *
	 */
	
	function drawForm(){
				
		// Load Templates
		$templates = new tpl_login_page( $this -> appCore);
				
		// Template values
		$tpl_vars = array(
			'act_code' => $this -> appCore -> session -> session_code,
			'act_key' => $this -> appCore -> session -> session_key,
			'user_login' => $this -> appCore -> _POST( 'user_login'),
			'user_email' => $this -> appCore -> _POST( 'user_email')
		);
		
		// Show reCAPTCHA?
		if ( $this -> appCore -> conf['recaptcha_on_register'])
		{
			$tpl_vars['show_captcha'] = $this -> appCore -> session -> session_code;
			$tpl_vars['captcha_html'] = $this -> recaptcha -> recaptcha_get_html( $this -> appCore);
		}
		
		// Draw Template
		$this -> appCore -> output -> draw( $this -> appCore -> lang['password_reset_title'], array(
			array( $this -> appCore -> niceLink( 'act=rpass', $this -> appCore -> lang['password_reset_title']),  $this -> appCore -> lang['password_reset_title'])
		), $templates -> tpl_reset_pass_form( $tpl_vars));
	
	}
	
}